from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional, List
from models.settings import Settings
from schemas.settings import SettingsCreate, SettingsUpdate
from sqlalchemy import select
from config import settings as app_settings

async def get_settings(db: AsyncSession) -> List[Settings]:
    """
    Get all settings with pagination.
    
    Args:
        db: Database session
        skip: Number of records to skip
        limit: Maximum number of records to return
        
    Returns:
        List of settings
    """
    return (await db.execute(select(Settings))).scalars().all()


async def create_settings(db: AsyncSession, settings: SettingsCreate) -> Settings:
    """
    Create new settings.
    
    Args:
        db: Database session
        settings: Settings data to create
        
    Returns:
        Created settings object
    """
    # 在Docker环境中，将localhost替换为host.docker.internal
    api_url = settings.api_url
    if app_settings.ENVIRONMENT == "docker" and api_url and "localhost" in api_url:
        api_url = api_url.replace("localhost", "host.docker.internal")
    
    db_settings = Settings(
        api_url=api_url,
        api_key=settings.api_key,
        model=settings.model
    )
    # 先删除，确保只有一个配置
    await delete_settings(db)

    db.add(db_settings)
    await db.commit()
    await db.refresh(db_settings)
    
    # 更新全局配置
    app_settings.OPENAI_API_KEY = settings.api_key
    app_settings.OPENAI_BASE_URL = api_url
    app_settings.OPENAI_MODEL = settings.model
    
    return db_settings


async def delete_settings(db: AsyncSession) -> bool:
    """
    Delete all settings.
    
    Args:
        db: Database session
        
    Returns:
        True if settings were deleted, False otherwise
    """
    db_settings = await get_settings(db)
    if db_settings:
        for setting in db_settings:
            await db.delete(setting)
        await db.commit()
        return True
    return False
